const User = require('../models/user.model.js');
const { strToHash } = require('../utils/index.js')
const jwt = require('jsonwebtoken')
class UserController {
    async getUser(ctx, next) {
        const data = await User.findAll({
            attributes:['id','name','email','createdAt','updatedAt']
        })
        ctx.body = {
            code: 200,
            message: "获取用户列表成功",
            data
        };
    }
    
    async createUser(ctx, next) {
        ctx.verifyParams({
            name: { type: "string", required: true },
            password: { type: "string", required: true },
            email: { type: "string", required: true }
        });
        const { name, email, password } = ctx.request.body;
        const repeatedUser = await User.findOne({ where: { name: name } });
        const repeatedEmail = await User.findOne({ where: { email: email } });
        if (repeatedUser) {  // 校验用户名是否已存在
            ctx.throw(409, "用户名已存在");
        }
        if (repeatedEmail) {  // 校验邮箱是否已存在
            ctx.throw(409, "邮箱已存在");
        }
        ctx.request.body.password = strToHash(password)
        const data = await User.build(ctx.request.body).save();
        ctx.body = data;
    }

    async login(ctx, next) {
        ctx.verifyParams({
            name: { type: "string", required: true },
            password: { type: "string", required: true }
        })
        const { name, password } = ctx.request.body;
        const user = await User.findOne({
            where: {
                name,
                password: strToHash(password)
            }
        });
        if (!user) {
            ctx.body = {
                code: 405,
                message: "用户名或密码错误",
            };
            return;
        }
        const token = jwt.sign(
            {
                name
            },
            "9527", // secret
            { expiresIn: 60 * 60 } // 60 * 60 s
        );
        ctx.body = {
            code: 200,
            message: "登录成功",
            data: {
                token,
                userInfo:user
            }
        };
    }
}
module.exports = new UserController();
